<?php

namespace Gaolei\YiiRBAC\controllers;

use Yii;
use yii\base\UserException;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use Gaolei\YiiRBAC\models\form\ChangePwd;
use Gaolei\YiiRBAC\models\form\Login;
use Gaolei\YiiRBAC\models\form\Signup;
use Gaolei\YiiRBAC\models\search\AdminerSearch;
use Gaolei\YiiRBAC\models\Adminer;

/**
 * User controller
 */
class AdminerController extends Controller
{

    private $_oldMailPath;

    private $admin;

    public function init()
    {
        parent::init();
        $this->admin = \Yii::$app->user->identity;
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['post'],
                    'logout' => ['post'],
                    'activate' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 检查是否能够操作账户
     * @param Adminer $user
     * @return bool
     * @author gaolei 2021/10/7 7:46 下午
     */
    protected function canOperate(Adminer $user): bool
    {
        if($this->admin->id !== 1){
            if ($user->id === $this->admin->getId()) {
                Yii::$app->session->setFlash('error', "管理员不能修改自己的账号");
                return false;
            } elseif ($user->id === 1) {
                Yii::$app->session->setFlash('error', "超级管理员不可修改");
                return false;
            } elseif ($this->admin->level < $user->level) {
                Yii::$app->session->setFlash('error', "你没有权限进行此操作");
                return false;
            }
        }
        return true;
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AdminerSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', ['model' => $this->findModel($id),]);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $user = $this->findModel($id);
        if ($this->canOperate($user)) {
            if ($user->delete()) {
                \Yii::$app->session->setFlash('success', '操作成功');
            } else {
                \Yii::$app->session->setFlash('danger', '操作失败');
            }
        }
        return $this->redirect(['index']);
    }

    /**
     * Login
     */
    public function actionLogin()
    {
        if (!Yii::$app->getUser()->isGuest) {
            return $this->goHome();
        }
        $model = new Login();
        if ($model->load(Yii::$app->getRequest()->post()) && $model->login()) {
            return $this->goBack();
        }
        return $this->render('login', ['model' => $model,]);
    }

    /**
     * Logout
     */
    public function actionLogout()
    {
        Yii::$app->getUser()->logout();
        return $this->goHome();
    }

    /**
     * Signup new user
     */
    public function actionSignup()
    {
        if ($this->admin->level < $this->admin::LEVE_ADMIN) {
            \Yii::$app->session->setFlash('warning', '没有权限进行该操作');
            return $this->goHome();
        }
        $model = new Signup();
        if ($model->load(Yii::$app->getRequest()->post()) && $model->signup()) {
            return $this->redirect(['index']);
        }
        return $this->render('signup', ['model' => $model,]);
    }

    /**
     * 重置账号密码
     */
    public function actionResetPwd(int $id, string $pwd)
    {
        if ($this->admin->level < $this->admin::LEVE_ADMIN) {
            \Yii::$app->session->setFlash('warning', '没有权限进行该操作');
            return $this->goHome();
        }
        if (!preg_match('/^[0-9A-Za-z]{6,16}$/', $pwd)) {
            \Yii::$app->session->setFlash('warning', '密码必须是由字母、数字组成的字符串[6~16]');

        }else{
            if ($user = $this->findModel($id)) {
                if (!$this->admin->id !== 1 && $this->admin->level <= $user->level) {
                    \Yii::$app->session->setFlash('warning', '没有权限进行该操作');
                } else {
                    $user->setPassword($pwd);
                    $user->generateAuthKey();
                    if ($user->save(false)) {
                        \Yii::$app->session->setFlash('success', '密码重置成功');
                    } else {
                        \Yii::$app->session->setFlash('error', '密码重置失败');
                    }
                }
            } else {
                \Yii::$app->session->setFlash('danger', '要操作的账户不存在');
            }
        }
        return $this->goBack();
    }

    /**
     * 修改当前账户密码
     */
    public function actionUpdatePwd()
    {
        $model = new ChangePwd();
        if ($model->load(Yii::$app->getRequest()->post()) && $model->updatePwd()) {
            return $this->goBack();
        }
        return $this->render('update-pwd', ['model' => $model]);
    }

    /**
     * 激活账户
     * @param integer $id
     * @return \yii\web\Response
     * @throws NotFoundHttpException
     * @throws UserException
     */
    public function actionActive(int $id): \yii\web\Response
    {
        if ($this->admin->level < $this->admin::LEVE_ADMIN) {
            return $this->goHome();
        }
        /* @var $user Adminer */
        $user = $this->findModel($id);
        if ($this->canOperate($user) && $user->state !== Adminer::STATE_ACTIVE) {
            $user->state = Adminer::STATE_ACTIVE;
            if (!$user->save()) {
                $errors = $user->firstErrors;
                throw new UserException(reset($errors));
            }
        }
        return $this->redirect(['index']);
    }

    /**
     * 禁用账户
     * @param integer $id
     * @return \yii\web\Response
     * @throws NotFoundHttpException
     * @throws UserException
     */
    public function actionDisable(int $id): \yii\web\Response
    {
        if ($this->admin->level < $this->admin::LEVE_ADMIN) {
            return $this->goHome();
        }
        /* @var $user Adminer */
        $user = $this->findModel($id);
        if ($this->canOperate($user) && $user->state !== Adminer::STATE_DISABLE) {
            $user->state = Adminer::STATE_DISABLE;
            if (!$user->save()) {
                $errors = $user->firstErrors;
                throw new UserException(reset($errors));
            }
        }
        return $this->redirect(['index']);
    }

    /**
     * @param $id
     * @return Adminer|null
     * @throws NotFoundHttpException
     * @author gaolei 2021/10/7 12:06 上午
     */
    protected function findModel($id): Adminer
    {
        if (($model = Adminer::findOne($id)) !== null) {
            return $model;
        }
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
